package com.zhuhjay.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuhjay.ruiji.common.R;
import com.zhuhjay.ruiji.common.ValidateCodeUtils;
import com.zhuhjay.ruiji.domain.User;
import com.zhuhjay.ruiji.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ZhuHJay
 * @date 2022/5/17 11:30
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 发送短信验证码...

        session.setAttribute(user.getPhone(), code);
        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody Map<String, Object> data){
        String phone = (String) data.get("phone");
//        String phoneCode = (String) session.getAttribute(phone);
//        if( phoneCode == null ){
//            return R.error("请先发送验证码");
//        }
//        String code = (String) data.get("code");
        // 校验验证码是否正确
//        if( !phoneCode.equals(code) ){
//            return R.error("验证码错误");
//        }

        // 用户是否存在数据库中, 不存在就创建新的
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone));
        if( user == null ){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("user", user.getId());
        return R.success(user);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
